<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Usuarios
 *
 * @author Ramiro
 */
class Usuarios {

    public function __construct() {
        
    }

    private function __clone() {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

    static public function getInstancia() {
        if (self::$instancia == NULL) {
            self::$instancia = new Connection();
        }
        return self::$instancia;
    }

    public function escapar($var) {
        $var = stripslashes($var);
        $var = htmlentities($var);
        $var = strip_tags($var);
        $var = addslashes($var);
        $var = mysql_real_escape_string($var);
        return $var;
    }

    public function insertar($username, $first_name, $last_name, $phone, $email) {

        $username = $this->escapar($username);
        $first_name = $this->escapar($first_name);
        $last_name = $this->escapar($last_name);
        $phone = $this->escapar($phone);
        $email = $this->escapar($email);

        $id = $this->maxId() + 1;
        //$SQL = "INSERT into usuario(Id,Username,Nombres,Apellidos,Telefono,Email) values ('$id','{$username}','{$first_name}','{$last_name}','{$phone}','{$email}')";
        $con = ConnectionSecure::getInstancia();
        $con->conectar();
        $dbconn = $con->getConexion();
        $query = $dbconn->prepare("INSERT into usuario(Id,Username,Nombres,Apellidos,Telefono,Email) values (?,?,?,?,?,?)");
        $query->bind_param("isssss", $id, $username, $first_name, $last_name, $phone, $email);

        if ($query->execute() == true) {
            $con->desconectar();
            return $id;
        } else {
            $con->desconectar();
            return -1;
        }
    }

    public function insertarRol($Idusuario, $type) {
        $type = $this->escapar($type);
        
        $Idusuario = $this->escapar($Idusuario);
        
        
        //$SQL_UPDATE = "insert into rol_usuario(Idusuario,Rol) values (?,?)";
        //('{$Idusuario}','{$type}')
        $con = ConnectionSecure::getInstancia();
        $con->conectar();
        $dbconn = $con->getConexion();
        $query = $dbconn->prepare("insert into rol_usuario(Idusuario,Rol) values (?,?)");
        $query->bind_param("is", $Idusuario, $type);

        if ($query->execute() == true) {
            $con->desconectar();
            return true;
        } else {
            $con->desconectar();
            return false;
        }
    }

    public function insertarClave($Idusuario, $pass) {

        $Idusuario=$this->escapar($Idusuario);        
        $pass=$this->escapar($pass);
        
        $con = ConnectionSecure::getInstancia();
        $con->conectar();
        $dbconn = $con->getConexion();
        $query = $dbconn->prepare("insert into clave(Idusuario,Password) values (?,?)");
        $query->bind_param("is", $Idusuario, $this->encodePass($pass));
        if ($query->execute() == true) {
            $con->desconectar();
            return true;
        } else {
            $con->desconectar();
            return false;
        }
    }

    public function maxId() {
        $SQL = 'SELECT  max(`id`) as id FROM `usuario` ';
        $con = Connection::getInstancia();
        $result = $con->obtenerQuery($SQL);
        if (!$result) {
            die('Could not run query: ' . mysql_error());
        }
        $row = mysql_fetch_assoc($result);
        if ($row) {
            return $row['id'];
        } else
            return 0;
    }
     
    public function usuario_valido($username, $password) {
        $username = $this->escapar($username);
        $password = $this->escapar($password);

        $con = ConnectionSecure::getInstancia();
        $con->conectar();
        $dbconn = $con->getConexion();
        $query = $dbconn->prepare("select id,Estado from usuario where Username=?");
        $query->bind_param("s", $username);
        $resultado = $query->execute();
        if ($resultado) {
            $query->bind_result($id, $Estado);
            $query->fetch();
            $con->desconectar();
            $con->conectar();
            $dbconn = $con->getConexion();

            if (!($query2 = $dbconn->prepare("select Idusuario from clave where Idusuario=? and Password=?"))) {
                echo "<script> alert('Prepare failed: (" . $dbconn->errno . ") " . $dbconn->error . ");</script>";
            }
            $pwd = $this->encodePass($password);
            $query2->bind_param("is", $id, $pwd);
            $idusuario = $id;
            $resultado2 = $query2->execute();

            if ($resultado2) {
                $query2->bind_result($idusuario);
                $query2->fetch();

                if (!isset($idusuario) || $idusuario < 0) {
                    return false;
                }
                if (isset($Estado)) {
                    if ($Estado == 'Aprobado') {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        } else {
            $con->desconectar();
            return false;
        }





        // 
    }

    public function aprobar($id) {        
        $con = ConnectionSecure::getInstancia();
        $id = $this->escapar($id);
        $con->conectar();
        $dbconn = $con->getConexion();
        $query = $dbconn->prepare("UPDATE `usuario` SET `Estado`='Aprobado' WHERE `id`=?");
        $query->bind_param("i", $id);
        if ($query->execute() == true) {
            $con->desconectar();
            return true;
        } else {
            $con->desconectar();
            return false;
        }
    }

    public function encodePass($pass) {
        return hash('sha512', $pass);
    }

    public function idFromUsuarioOrEmail($usuario, $email) {

        $usuario = $this->escapar($usuario);
        $email = $this->escapar($email);
        $con = ConnectionSecure::getInstancia();
        $con->conectar();
        $dbconn = $con->getConexion();
        $query = $dbconn->prepare("SELECT  `id` FROM `usuario` WHERE  `Username` =? or  `Email` =?");
        $query->bind_param("ss", $usuario, $email);
        if ($query->execute() == true) {
            $query->bind_result($id);
            $query->fetch();
            $con->desconectar();
            if (isset($id) && $id > 0) {
                return $id;
            } else
                return '-1';
        } else {
            $con->desconectar();
            return '-1';
        }
    }

    public function idFromUsuario($usuario) {
        $usuario = $this->escapar($usuario);
        $con = ConnectionSecure::getInstancia();
        $con->conectar();
        $dbconn = $con->getConexion();
        $query = $dbconn->prepare("SELECT  `id` FROM `usuario` WHERE  `Username` =?  limit 1;");
        $query->bind_param("s", $usuario);
        if ($query->execute() == true) {
            $query->bind_result($id);
            $query->fetch();
            $con->desconectar();
            if (isset($id) && $id > 0) {
                return $id;
            } else
                return '-1';
        } else {
            $con->desconectar();
            return '-1';
        }
    }

    public function consultarUsuariosInactivos() {
        //const SQL_UPDATE='SELECT * FROM `transaccion` WHERE `ESTADO`='. $estado . ';';        
        $SQL_UPDATE = 'SELECT `id`,`Username`,`Nombres`,`Apellidos`,`Email` FROM `usuario` WHERE `Estado`="No_Aprobado";';
        $con = Connection::getInstancia();
        return $con->obtenerQuery($SQL_UPDATE);
    }

}

?>
